<template>
  <div class="app-container">
    <el-collapse-transition>
      <el-card v-show="isFilterVisible" class="search-wrapper">
        <div>
          <el-form
            :model="selContractListQuery"
            :inline="true"
            label-width="auto"
          >
            <div class="form-row">
              <el-form-item label="项目名称">
                <el-input
                  v-model="selContractListQuery.PName"
                  clearable
                  placeholder="请输入项目名称"
                />
              </el-form-item>
              <el-form-item label="客户单位">
                <!-- <el-select
                  @change="handleCustomerChange"
                  clearable
                  v-model="selContractListQuery.customer"
                  placeholder="请选择客户单位"
                  style="width: 177px"
                >
                  <el-option
                    :label="item.name"
                    :value="item.name"
                    v-for="item in customerUnits"
                    :key="item.id"
                  ></el-option>
                </el-select> -->
                <el-input
                  v-model="selContractListQuery.customer"
                  clearable
                  placeholder="请输入客户单位"
                />
              </el-form-item>
              <el-form-item label="客户类型">
                <el-select
                  v-model="selContractListQuery.customerType"
                  clearable
                  placeholder="请选择客户类型"
                  style="width: 177px"
                  @change="handleCustomerTypeChange"
                >
                  <el-option
                    v-for="item in projectTypes"
                    :key="item.id"
                    :label="item.name"
                    :value="item.name"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="项目领域">
                <el-select
                  v-model="selContractListQuery.projectArea"
                  clearable
                  placeholder="请选择项目领域"
                  style="width: 177px"
                  @change="handleProjectAreaChange"
                >
                  <el-option
                    v-for="item in projectAreas"
                    :key="item.id"
                    :label="item.name"
                    :value="item.name"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="存量类型">
                <el-select
                  v-model="selContractListQuery.stockType"
                  clearable
                  placeholder="请选择存量类型"
                  style="width: 177px"
                  @change="handleStockTypeChange"
                >
                  <el-option label="存量" value="存量" />
                  <el-option label="增量" value="增量" />
                </el-select>
              </el-form-item>
              <el-form-item label="重点项目">
                <el-select
                  v-model="selContractListQuery.isImportant"
                  clearable
                  placeholder="请选择重点项目"
                  style="width: 177px"
                  @change="handleImportantChange"
                >
                  <el-option label="是" value="是" />
                  <el-option label="否" value="否" />
                </el-select>
              </el-form-item>
              <el-form-item label="内容及要求">
                <el-input
                  v-model="selContractListQuery.content"
                  clearable
                  placeholder="请输入内容及要求"
                />
              </el-form-item>
              <el-form-item label="合同编码">
                <el-input
                  v-model="selContractListQuery.no"
                  clearable
                  placeholder="请输入合同编码"
                />
              </el-form-item>
              <el-form-item label="审批状态">
                <el-select
                  v-model="selContractListQuery.status"
                  clearable
                  placeholder="请选择审批状态"
                  style="width: 177px"
                  @change="handleStatusChange"
                >
                  <el-option
                    v-for="item in prStatusOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button
                  type="primary"
                  icon="el-icon-search"
                  @click="handleQuery"
                >搜索</el-button>
                <el-button
                  icon="el-icon-refresh"
                  @click="resetQuery"
                >重置</el-button>
              </el-form-item>
            </div>
          </el-form>
        </div>
      </el-card>
    </el-collapse-transition>
    <el-card>
      <!-- 顶部操作按钮 -->
      <div class="operation-container">
        <el-button
          type="primary"
          size="small"
          class="filter-trigger"
          @click="isFilterVisible = !isFilterVisible"
        >{{ isFilterVisible ? "收起" : "检索" }}
          <i
            :class="['el-icon-arrow-down', { 'is-reverse': isFilterVisible }]"
          />
        </el-button>
        <!-- <el-button
          type="success"
          icon="el-icon-back"
          size="small"
          @click="handleBack"
          >撤回</el-button
        > -->
      </div>

      <!-- 表格 -->
      <el-table
        ref="multipleTable"
        v-loading="loading"
        :data="selContractLists"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column
          label="序号"
          width="70"
          type="index"
          align="center"
        />
        <el-table-column prop="no" label="合同编号" width="120" />
        <el-table-column
          prop="pname"
          label="项目名称"
          min-width="250"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          prop="customer"
          label="客户单位"
          min-width="200"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          prop="money"
          label="合同金额(元)"
          width="120"
          align="center"
        />
        <el-table-column
          prop="salesman"
          label="项目负责人"
          width="120"
        />
        <el-table-column
          prop="createTime"
          label="创建时间"
          width="150"
          align="center"
        >
          <template slot-scope="scope">
            {{ formatCreateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="项目状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="getProjectStatusType(scope.row.status)">{{
              getProjectStatus(scope.row.status)
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" align="center">
          <template slot-scope="scope">
            <el-button
              type="success"
              size="small"
              :disabled="Number(scope.row.status) >= 4"
              @click="handleApprove(scope.row)"
            >审批</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-row style="margin-top: 20px" type="flex" justify="end">
        <el-pagination
          background
          :current-page="selContractListQuery.page"
          :page-sizes="[10, 20, 30, 40, 50]"
          :page-size="selContractListQuery.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-row>
    </el-card>

    <!-- 添加项目办结弹框 -->
    <el-dialog
      title="项目办结"
      :visible.sync="dialogVisible"
      width="87%"
      @close="handleDialogClose"
    >
      <!-- 项目标题和折叠面板 -->
      <div class="dialog-content-wrapper">
        <div class="collapse-header">
          <h3>北仑区传媒中心经营项目立项</h3>
          <!-- <span class="view-btn">点击查看</span> -->
        </div>
        <el-card>
          <!-- <div slot="header"></div> -->
          <div>
            <div class="detail-content">
              <div class="contract-no">
                合同编号：{{ projectDetail.no || "" }}
              </div>
              <el-form label-width="100px" class="detail-form">
                <el-row :gutter="0">
                  <el-col :span="12">
                    <el-form-item label="项目类型">
                      <el-input
                        v-model="projectDetail.ptype"
                        disabled
                        style="width: 100%"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="项目名称">
                      <el-input
                        v-model="projectDetail.pname"
                        disabled
                        style="width: 100%"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="0">
                  <el-col :span="12">
                    <el-form-item label="项目采购方式">
                      <el-input
                        v-model="projectDetail.projectFrom"
                        disabled
                        style="width: 100%"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="客户类型">
                      <el-input
                        v-model="projectDetail.customerType"
                        disabled
                        style="width: 100%"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="0">
                  <el-col :span="12">
                    <el-form-item label="客户单位">
                      <el-input
                        v-model="projectDetail.customer"
                        disabled
                        style="width: 100%"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="项目领域">
                      <el-input
                        v-model="projectDetail.projectArea"
                        disabled
                        style="width: 100%"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="0">
                  <el-col :span="12">
                    <el-form-item label="项目负责人">
                      <el-input
                        v-model="projectDetail.salesman"
                        style="width: 100%"
                        disabled
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="执行时间">
                      <el-input
                        v-model="projectDetail.duration"
                        disabled
                        style="width: 100%"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="0">
                  <el-col :span="12">
                    <el-form-item label="项目成本">
                      <el-input
                        v-model="projectDetail.cost"
                        style="width: 100%"
                        disabled
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="合同金额">
                      <el-input
                        v-model="projectDetail.money"
                        disabled
                        style="width: 100%"
                      >
                        <template slot="append">元</template>
                      </el-input>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="0">
                  <el-col :span="12">
                    <el-form-item label="实际收入">
                      <el-input
                        v-model="projectDetail.receiveMoney"
                        style="width: 100%"
                        disabled
                      >
                        <template slot="append">元</template>
                      </el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="存量类型">
                      <el-input
                        v-model="projectDetail.stockType"
                        disabled
                        style="width: 100%"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="0">
                  <el-col :span="12">
                    <el-form-item label="到账金额">
                      <el-input
                        v-model="projectDetail.receiveMoney"
                        disabled
                        style="width: 100%"
                      >
                        <template slot="append">元</template>
                      </el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="项目奖励">
                      <el-input
                        v-model="projectDetail.manageRate"
                        disabled
                        style="width: 100%"
                      >
                        <template slot="append">%</template>
                      </el-input>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="0">
                  <el-col :span="24">
                    <el-form-item label="内容及要求">
                      <el-input
                        v-model="projectDetail.content"
                        type="textarea"
                        :rows="4"
                        disabled
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
          </div>
        </el-card>
        <!-- 项目基本信息表单 -->
        <!-- </el-collapse-item>
      </el-collapse> -->
        <el-card style="margin-top: 20px">
          <!-- <div slot="header"></div> -->
          <div>
            <div class="project-type">
              <div class="type-title">项目类型</div>
              <el-table
                :header-cell-style="{ background: '#f5f7fa' }"
                :data="projectDetail.list || []"
                border
                style="width: 100%"
              >
                <el-table-column
                  prop="platform"
                  label="平台产品IP"
                  width="width"
                  align="center"
                />
                <el-table-column
                  prop="department"
                  label="执行事业部"
                  width="200"
                  align="center"
                />
                <el-table-column
                  prop="content"
                  label="执行内容及要求"
                  width="300"
                  align="center"
                />
                <el-table-column prop="attribute" label="属性" align="center" />
                <el-table-column prop="money" label="金额" align="center">
                  <template slot-scope="scope">
                    {{ scope.row.money || "0" }}
                  </template>
                </el-table-column>
                <!-- <el-table-column
                  prop="estimatedCost"
                  width="100"
                  label="直接成本"
                  align="center"
                >
                  <template slot-scope="scope">
                    {{ scope.row.estimatedCost || "0" }}
                  </template>
                </el-table-column> -->
                <el-table-column
                  prop="transferCompany"
                  label="划转对象"
                  width="width"
                  align="center"
                >
                  <template slot-scope="scope">
                    <el-select
                      v-model="scope.row.transferCompany"
                      clearable
                      placeholder="请选择划转对象"
                      size="small"
                      style="width: 100%"
                      @change="handleTransferCompanyChange($event, scope.row)"
                    >
                      <el-option
                        v-for="item in transferObjectList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.name"
                      />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="transferMoney"
                  label="划转金额"
                  width="width"
                  align="center"
                >
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row.transferMoney"
                      clearable
                      size="small"
                      style="width: 100%"
                      placeholder="请输入划转金额"
                      @change="handleTransferMoneyChange($event, scope.row)"
                    />
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-card>

        <el-card style="margin-top: 20px">
          <!-- <div slot="header"></div> -->
          <div style="border: 2px solid #ebeef5">
            <div class="contract-info">
              <div class="info-item">
                <div class="info-label">合同电子版</div>
                <div class="info-content">
                  <a
                    v-if="projectDetail.contractFile"
                    :href="projectDetail.contractFile"
                    class="download-link"
                    @click.prevent="
                      handleFileDownload(projectDetail.contractFile)
                    "
                  >
                    {{ getFileName(projectDetail.contractFile) }}(点击下载文件)
                  </a>
                  <div class="button-group">
                    <el-button
                      type="primary"
                      size="small"
                      @click="handleFileDownload(projectDetail.contractFile)"
                    >下载</el-button>
                    <el-button
                      size="small"
                      @click="handlePreview"
                    >预览</el-button>
                  </div>
                </div>
              </div>
              <div class="info-item">
                <div class="info-label">负责人备注</div>
                <div class="info-content">
                  {{ projectDetail.remarks || "" }}
                </div>
              </div>
              <div class="info-item">
                <div class="info-label">项目立项意见</div>
                <div class="info-content">
                  {{ projectDetail.lsuggest || "" }}
                </div>
              </div>
              <!-- <div class="info-item">
                <div class="info-label">项目立项人</div>
                <div class="info-content">
                  {{ projectDetail.luser || "" }}
                </div>
              </div> -->
              <div class="info-item">
                <div class="info-label">项目立项时间</div>
                <div class="info-content">
                  {{ formatCreateTime(projectDetail.ltime) || "" }}
                </div>
              </div>
            </div>
          </div>
        </el-card>
        <!-- 计财部填报表单 -->
      </div>

      <el-card style="margin-top: 20px">
        <div slot="header" class="type-title">立项初审</div>
        <el-form
          ref="formRef"
          :model="approvalInfo"
          :rules="rules"
          label-width="134px"
          style="margin-top: 20px"
        >
          <el-form-item label="项目是否立项">
            <!-- <div class="item-label">是否同意签订合同</div> -->
            <!-- <div class="item-content"> -->
            <el-radio-group v-model="approvalInfo.result">
              <el-radio label="立项" value="立项" />
              <el-radio label="反驳" value="反驳" />
            </el-radio-group>
            <!-- </div> -->
          </el-form-item>

          <el-form-item label="审批意见">
            <el-input
              v-model="approvalInfo.suggest"
              type="textarea"
              :rows="4"
              placeholder="请输入审批意见"
            />
          </el-form-item>
        </el-form>
      </el-card>
      <!-- </div>
      </div> -->

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { selContractListApi, addContractByIdApi } from '@/api/project-approval'
import { uploadFileApi, selFileUrlApi, selTemplateApi } from '@/api/uploadFile'
import {
  selCustomerTypeListApi, // 客户类型列表查询
  selCustomerUnitListApi, // 客户单位列表查询
  selProjectAreaListApi, // 项目领域列表查询
  selTransferObjectListApi // 划转对象列表查询
} from '@/api/basic-data'
import { mapGetters } from 'vuex'
export default {
  name: 'ProjectApproval',
  data() {
    return {
      tableData: [
        {
          id: 1,
          contractNo: '202501181',
          projectName: '供销社年度合作项目',
          customerUnit: '宁波市北仑区供销社有限公司',
          contractAmount: 296000,
          projectManager: '杜倩',
          status: '待审批',
          createTime: '2025-01-18 00:00'
        }
      ],
      // 合同初审查询参数
      queryParams: {
        page: 1,
        pageSize: 10,
        status: 1, // 项目状态
        customer: '', // 客户
        no: '', // 合同编号
        PName: '', // 项目名称
        customerType: '', // 客户类型
        projectArea: '', // 项目领域
        stockType: '', // 存量类型
        isImportant: '', // 重点项目
        content: '' // 内容及要求
      },
      // 合同列表
      selContractLists: [],
      // 项目状态
      prStatusOptions: [
        { label: '待评审', value: 1 },
        { label: '已同意', value: 2 },
        { label: '已驳回', value: 3 }
      ],
      // 是否到账
      accountOptions: [
        { label: '未到账', value: '1' },
        { label: '部分到账', value: '0' },
        { label: '已到账', value: '2' }
      ],
      // 合同列表查询参数
      selContractListQuery: {
        page: 1,
        pageSize: 10,
        status: 1, // 项目状态
        content: '', // 	内容及要求
        customer: '', // 客户
        customerType: '', // 客户类型
        isImportant: '', // 重点项目
        no: '', // 合同编号
        PName: '', // 项目名称
        projectArea: '', // 项目区域
        stockType: '' // 存量类型
      },
      // 审批信息
      approvalInfo: {
        list: [], // 初始化为空数组，根据返回的数据动态生成
        result: '立项',
        suggest: '同意立项',
        userId: this.$store.getters.userId
      },
      // 项目信息
      projectInfo: {
        name: '北仑区纪律检查委员会《党风廉政建设专题片》',
        executeTime: '2024-12-13至2025-01-24',
        customerType: '政府',
        customerUnit: '中国共产党宁波市北仑区纪律检查委员会',
        projectField: '党建群团',
        stockType: '存量',
        isKeyProject: '否',
        contractAmount: '200000',
        manager: '张强',
        managementAward: '2',
        requirements:
          '1、甲方委托乙方拍摄制作《党风廉政建设专题片》一部，时长23分钟左右，根据实际情况确定。\n2、根据片子要求，乙方实行保密措施，确保文稿、镜头、配音等相关素材等不流传摄制组之外。'
      },
      projectTypeList: [
        {
          productIp: '*视频',
          department: '视觉影像事业部',
          requirements:
            '1、甲方委托乙方拍摄制作《党风廉政建设专题片》一部，时长23分钟左右，根据实际情况确定。2、根据片子要求，乙方实行保密措施...',
          property: '执行类',
          amount: '200000',
          directCost: '0',
          transferCompany: '无',
          transferAmount: '0',
          transferNote: ''
        }
      ],
      completionInfo: [
        {
          wordContract:
            '中共宁波市北仑纪律检查委员会视频摄制合作协议(1)(2).doc(点击下载文件)',
          remark: '备注',
          completionDesc:
            '按要求拍摄制作完成《党风廉政建设专题片》一部，时长20分钟。',
          closePerson: '张强',
          closeDate: '2025-02-05',
          customerSatisfaction: '满意',
          serviceOpinion: '同意'
        }
      ],
      formData: {
        isApproved: null,
        remark: ''
      },
      // rules: {
      //   isApproved: [
      //     {
      //       required: true,
      //       message: "请选择是否同意签订合同",
      //       trigger: "change",
      //     },
      //   ],
      //   remark: [
      //     { required: true, message: "请输入初审意见", trigger: "blur" },
      //   ],
      // },
      dialogVisible: false,
      isFilterVisible: false,
      // 客户类型列表参数
      selCustomerTypeListQuery: {
        page: 1,
        pageSize: 10,
        name: ''
      },
      projectTypes: [], // 客户类型列表
      customerUnits: [], // 客户单位列表
      projectAreas: [], // 项目领域列表
      total: 0, // 总条数
      projectDetail: {}, // 项目详情
      id: '' // 项目id
    }
  },
  computed: {
    ...mapGetters(['userId'])
  },
  watch: {
    'approvalInfo.result': {
      handler(newVal) {
        console.log(newVal)
        if (newVal === '立项') {
          this.approvalInfo.suggest = '同意立项'
        } else {
          this.approvalInfo.suggest = ''
        }
      },
      immediate: true
    }
  },
  created() {
    console.log(this.$route.query.no)
    if (this.$route.query.no) {
      this.selContractListQuery.no = this.$route.query.no
    }
    this.selContractList() // 合同列表查询
    this.selCustomerTypeList() // 客户类型列表
    this.selProjectAreaList() // 项目领域列表
    this.selCustomerUnitList() // 客户单位列表
    this.selTransferObjectList() // 划转对象列表查询
  },
  methods: {
    // 划转对象列表查询
    async selTransferObjectList() {
      const res = await selTransferObjectListApi(this.selCustomerTypeListQuery)
      console.log(res)
      this.transferObjectList = res.records
    },
    // 处理文件下载
    handleFileDownload(url) {
      if (!url) {
        this.$message.warning('文件链接不存在')
        return
      }

      // 拼接完整的下载地址
      // const baseUrl = "http://192.168.11.22:38085";
      const baseUrl = 'http://192.168.11.2:8081'
      const fullUrl = `${baseUrl}${url}`

      // 获取文件名 - 截取_后面的部分
      const fileName = url.split('_').pop()
      console.log(fullUrl)

      try {
        const link = document.createElement('a')
        link.style.display = 'none'
        link.href = fullUrl
        link.setAttribute('download', fileName) // 使用新的文件名
        document.body.appendChild(link)

        link.click()

        document.body.removeChild(link)
      } catch (error) {
        console.error('下载失败:', error)
        this.$message.error('下载失败，请重试')
      }
    },
    // 处理文件预览
    async handlePreview() {
      if (!this.projectDetail.contractFile) {
        this.$message.warning('文件链接不存在')
        return
      }
      try {
        // 获取预览链接
        const res = await selFileUrlApi(this.projectDetail.contractFile)
        console.log(res)
        if (res.code === 1 && res.data) {
          // 在新窗口中打开预览链接
          window.open(res.data, '_blank')
        } else {
          this.$message.error(res.msg || '获取预览链接失败')
        }
      } catch (error) {
        console.error('预览失败:', error)
        this.$message.error('预览失败，请重试')
      }
    },
    // 获取文件名
    getFileName(url) {
      if (!url) return ''
      // 截取_后面的部分作为文件名
      console.log(url.split('_').pop())
      return url.split('_').pop()
    },
    // 客户类型列表查询
    async selCustomerTypeList() {
      const res = await selCustomerTypeListApi(this.selCustomerTypeListQuery)
      console.log(res)
      this.projectTypes = res.records
    },
    // 客户单位列表查询
    async selCustomerUnitList() {
      const res = await selCustomerUnitListApi(this.selCustomerTypeListQuery)
      console.log(res)
      this.customerUnits = res.records
    },
    // 项目领域列表查询
    async selProjectAreaList() {
      const res = await selProjectAreaListApi(this.selCustomerTypeListQuery)
      console.log(res)
      this.projectAreas = res.records
    },
    // 获取合同列表
    async selContractList() {
      this.loading = true
      try {
        const res = await selContractListApi(this.selContractListQuery)
        console.log(res)
        this.selContractLists = res.records
        console.log(this.selContractLists)
        this.total = res.total
      } catch (error) {
        console.error('获取合同列表失败:', error)
        this.$message.error('获取合同列表失败')
      } finally {
        this.loading = false
      }
    },
    // 搜索
    handleQuery() {
      this.selContractListQuery.page = 1
      console.log('查询参数：', this.selContractListQuery)
      this.selContractList()
    },
    // 分页
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.selContractListQuery.pageSize = val
      this.selContractList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.selContractListQuery.page = val
      this.selContractList()
    },
    // 审批
    handleApprove(row) {
      this.dialogVisible = true
      this.projectDetail = row
      this.id = row.id

      // 根据返回的list数据初始化approvalInfo.list
      if (row.list && Array.isArray(row.list)) {
        this.approvalInfo.list = row.list.map((item) => ({
          projectDetailId: item.id, // 使用list中的id
          transferCompany: item.transferCompany || '无', // 初始化为空字符串
          transferMoney: Number(item.transferMoney || 0) // 初始化为0
        }))
      }
    },
    // 查询
    handleQuery() {
      this.selContractListQuery.page = 1
      this.selContractList()
    },
    resetQuery() {
      (this.selContractListQuery = {
        page: 1,
        pageSize: 10,
        status: 1, // 项目状态
        customer: '', // 客户
        no: '', // 合同编号
        PName: '', // 项目名称
        customerType: '', // 客户类型
        projectArea: '', // 项目领域
        stockType: '', // 存量类型
        isImportant: '', // 重点项目
        content: '' // 内容及要求
      }),
      this.selContractList()
    },
    // 关闭弹框
    handleDialogClose() {
      console.log(1234)

      // 清空projectDetail.list中的划转对象和划转金额
      if (this.projectDetail.list && Array.isArray(this.projectDetail.list)) {
        this.projectDetail.list = this.projectDetail.list.map((item) => ({
          ...item,
          transferCompany: null, // 清空划转对象
          transferMoney: null // 清空划转金额
        }))
      }

      // 重置审批信息
      this.approvalInfo = {
        list: [],
        result: '立项',
        suggest: '同意立项',
        userId: this.$store.getters.userId
      }
    },

    // 格式化创建时间
    formatCreateTime(time) {
      if (!time) return ''
      // 找到第二个冒号的位置并截取字符串
      const secondColonIndex = time.indexOf(':', time.indexOf(':') + 1)
      return time.substring(0, secondColonIndex)
    },
    // 封装获取项目状态
    getProjectStatus(status) {
      if (status === null || status === undefined) return ''

      const statusNum = Number(status)
      if (statusNum >= 4) {
        return '已同意'
      } else if (statusNum === 1) {
        return '待审批'
      } else if (statusNum === -1) {
        return '已驳回'
      }
      return ''
    },
    // 封装获取项目状态类型
    getProjectStatusType(status) {
      if (status === null || status === undefined) return ''

      const statusNum = Number(status)
      if (statusNum >= 4) {
        return 'success' // 绿色
      } else if (statusNum === 1) {
        return 'warning' // 黄色
      } else if (statusNum === -1) {
        return 'danger' // 红色
      }
      return 'info' // 默认灰色
    },
    // 客户类型改变
    handleCustomerTypeChange(val) {
      console.log('客户类型改变', val)
      this.selContractList()
    },
    // 项目领域改变
    handleProjectAreaChange(val) {
      console.log('项目领域改变', val)
      this.selContractList()
    },
    // 存量类型改变
    handleStockTypeChange(val) {
      console.log('存量类型改变', val)
      this.selContractList()
    },
    // 重点项目改变
    handleImportantChange(val) {
      console.log('重点项目改变', val)
      this.selContractList()
    },
    // 审批状态改变
    handleStatusChange(val) {
      console.log('审批状态改变', val)
      this.selContractList()
    },
    // 客户单位改变
    handleCustomerChange(val) {
      console.log('客户单位改变', val)
      this.selContractList()
    },
    // 处理划转对象变化
    handleTransferCompanyChange(value, row) {
      console.log('划转对象改变', value, row)
      // 查找当前行对应的approvalInfo.list项
      const index = this.approvalInfo.list.findIndex(
        (item) => item.projectDetailId === row.id
      )
      console.log(index)

      if (index > -1) {
        // 如果存在，更新值
        this.approvalInfo.list[index].transferCompany = value || '无'
      }
    },

    // 处理划转金额变化
    handleTransferMoneyChange(value, row) {
      // 查找当前行对应的approvalInfo.list项
      const index = this.approvalInfo.list.findIndex(
        (item) => item.projectDetailId === row.id
      )

      if (index > -1) {
        // 如果存在，更新值
        this.approvalInfo.list[index].transferMoney = Number(value || 0)
      }
    },

    // 提交时不需要再次处理list数据，因为已经在change事件中处理过了
    async handleSubmit() {
      try {
        await this.$refs.formRef.validate()

        const res = await addContractByIdApi(this.approvalInfo, this.id)
        if (res.code === 1) {
          this.$message.success('提交成功')
          this.dialogVisible = false
          this.selContractList()
        } else {
          this.$message.error(res.msg || '提交失败')
        }
      } catch (error) {
        console.error('提交失败:', error)
        this.$message.error('表单验证失败，请检查必填项')
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.operation-container {
  margin-bottom: 20px;
}

.operation-container .el-button {
  margin-right: 10px;
}

.filter-trigger .el-icon-arrow-down {
  margin-left: 5px;
  transition: transform 0.3s;
}

.filter-trigger .el-icon-arrow-down.is-reverse {
  transform: rotate(180deg);
}

.search-wrapper {
  margin-bottom: 20px;
}

/* 确保表格内容不会被截断 */
.el-table .cell {
  white-space: nowrap;
}

/* 调整按钮样式 */
.el-button--text {
  padding: 0;
  margin: 0;
}

/* 调整表格行高 */
.el-table td {
  padding: 8px 0;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

/* 项目标题和折叠面板样式 */
.project-title {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  font-size: 14px;
}

.view-text {
  color: #409eff;
  font-size: 13px;
}

.contract-number {
  font-size: 14px;
  color: #409eff;
  margin-bottom: 20px;
}

.project-form {
  margin-bottom: 20px;
}

.table-title {
  font-size: 16px;
  font-weight: bold;
  margin: 20px 0;
}

.project-detail {
  padding: 20px;
  background-color: #fafafa;
}

.file-cell {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.file-name {
  color: #409eff;
  cursor: pointer;
}

.person-cell {
  display: flex;
  flex-direction: column;
}

.close-date {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

/* Element UI 组件样式覆盖 */
:deep(.el-collapse) {
  border: none;
}

:deep(.el-collapse-item__header) {
  background-color: #f5f7fa;
  padding: 0 20px;
  border: none;
}

:deep(.el-collapse-item__content) {
  padding: 0;
}

:deep(.el-form-item__label) {
  font-weight: normal;
  color: #606266;
}

:deep(.el-input.is-disabled .el-input__inner) {
  color: #303133;
}

:deep(.el-textarea.is-disabled .el-textarea__inner) {
  color: #303133;
}

:deep(.el-table__cell) {
  vertical-align: middle;
}

:deep(.el-button--mini) {
  margin: 0;
}

.type-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  // margin-bottom: 20px;
  padding-left: 10px;
  border-left: 4px solid #409eff;
}

.el-input {
  width: 177px;
}

.amount {
  font-size: 16px;
  color: #f56c6c;
  font-weight: bold;
}

.unit {
  margin-left: 5px;
  color: #606266;
}

.approval-form {
  padding: 20px;
  background: #fff;

  .form-title {
    font-size: 16px;
    font-weight: bold;
    color: #303133;
    margin-bottom: 24px;
    position: relative;

    &::after {
      content: "";
      position: absolute;
      left: 0;
      bottom: -12px;
      width: 100%;
      height: 1px;
      background-color: #ebeef5;
    }
  }

  .form-content {
    padding: 20px 0;

    :deep(.el-form-item) {
      margin-bottom: 24px;

      &:last-child {
        margin-bottom: 0;
      }
    }
  }

  .item-label {
    font-size: 14px;
    color: #606266;
    margin-bottom: 12px;
  }

  .item-content {
    .el-textarea {
      width: 100%;
    }
  }
}

.collapse-header {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 16px;
  color: #303133;

  .view-btn {
    color: #409eff;
    font-size: 14px;
    cursor: pointer;
  }
}

.detail-content {
  background: #fff;
  // border: 2px solid #ebeef5;
  // margin-top: 20px;

  .contract-no {
    color: #1b86ee;
    font-size: 16px;
    margin: 20px;
  }
}

.project-type {
  margin-top: 20px;

  .type-title {
    font-size: 16px;
    font-weight: bold;
    color: #303133;
    margin-bottom: 20px;
    padding-left: 10px;
    border-left: 4px solid #409eff;
  }

  :deep(.el-table) {
    th {
      background-color: #f5f7fa;
      color: #606266;
      padding: 8px 0;
      font-weight: normal;
    }

    td {
      padding: 8px;
      color: #606266;
    }

    &::before,
    &::after {
      background-color: #ebeef5;
    }

    .el-table__cell {
      border-color: #ebeef5;
    }
  }
}
.contract-info {
  // margin-top: 40px;
  // border: 2px solid #ebeef5;
  border-radius: 4px;

  .info-item {
    display: flex;
    border-bottom: 1px solid #ebeef5;

    &:last-child {
      border-bottom: none;
    }

    .info-label {
      width: 120px;
      padding: 12px;
      background-color: #f5f7fa;
      color: #606266;
      font-size: 14px;
      border-right: 1px solid #ebeef5;
    }

    .info-content {
      flex: 1;
      padding: 12px;
      min-height: 44px;
      display: flex;
      align-items: center;
      color: #606266;
      font-size: 14px;

      &:has(.download-link) {
        justify-content: space-between;
      }

      .download-link {
        color: #409eff;
        text-decoration: none;

        &:hover {
          text-decoration: underline;
        }
      }

      .button-group {
        .el-button {
          margin-left: 10px;
        }
      }
    }
  }
}

.type-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  // margin-bottom: 20px;
  padding-left: 10px;
  border-left: 4px solid #409eff;
}

// 调整输入框样式
:deep(.el-input-number) {
  width: 100%;
}

:deep(.el-input__inner) {
  text-align: left;
}
</style>
